package com.bw.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.utils.DateFormatUtil;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.util.Collector;


public class DwdShopUv {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        String topic = "dwd_traffic";
        String groupId = "dwd_traffic";
        FlinkKafkaConsumer<String> kafkaConsumer = MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId);
        DataStreamSource<String> pageLog = env.addSource(kafkaConsumer);
        SingleOutputStreamOperator<String> pages = pageLog.filter(new FilterFunction<String>() {
            @Override
            public boolean filter(String s) throws Exception {
                JSONObject jsonObject = JSON.parseObject(s);
                if (jsonObject.getJSONObject("page") != null) {
                    String string = jsonObject.getJSONObject("page").getString("page_action");
                    if (string.equals("a") ||
                            string.equals("b") ||
                            string.equals("c") ||
                            string.equals("e") ||
                            string.equals("f")) {
                        return true;
                    }
                    return false;
                } else {
                    return false;
                }

            }
        });


        //todo 3.转换结构
        SingleOutputStreamOperator<JSONObject> mappedStream = pages.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    JSONObject jsonObj = JSON.parseObject(s);
                    collector.collect(jsonObj);
                } catch (Exception e) {
                    System.out.println("脏数据:" + s);
                }
            }
        });

        //todo 4. 过滤last_page_id 不为null的数据
        SingleOutputStreamOperator<JSONObject> firstPageStream = mappedStream.filter(x -> x.getJSONObject("page")
                .getString("last_page_id") == null
        );

        //todo5. 按照mid分组
        KeyedStream<JSONObject, String> keyedStream = firstPageStream.keyBy(x -> x.getJSONObject("common")
                .getString("mid")
        );

        //todo 6. 通过flink状态编程过滤独立访客记录
        SingleOutputStreamOperator<JSONObject> filteredStream = keyedStream.filter(new RichFilterFunction<JSONObject>() {
            private ValueState<String> lastVisitDt;

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);
                ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("last_visit_dt", String.class);

                valueStateDescriptor
                        .enableTimeToLive(StateTtlConfig
                                .newBuilder(Time.days(1L))
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                .build());
                this.lastVisitDt = getRuntimeContext().getState(valueStateDescriptor);
            }

            @Override
            public boolean filter(JSONObject jsonObject) throws Exception {
                String visitDt = DateFormatUtil.toDate(jsonObject.getLong("ts"));
                String lastDt = lastVisitDt.value();
                if (lastDt == null || !lastDt.equals(visitDt)) {
                    lastVisitDt.update(visitDt);
                    return true;
                }
                return false;
            }
        });

        //todo 7.将独立访客数据写入
        String targetTopic="dwd_Shop_uv";
        filteredStream.print(">>>>>>>>>>>>>>>>>");
        FlinkKafkaProducer<String> kafkaProducer = MyKafkaUtil.getFlinkKafkaProducer(targetTopic);
        filteredStream.map(a->a.toJSONString()).addSink(kafkaProducer);




        env.execute();

    }
}
